<script>
import Vue from "vue";
import logger from "./utils/logger";
import config from "./common/api/config.js";
import { timInit } from "./utils/tim";
export default {
  data() {
    return {
      version: "1.0.0", //版本名称
      versionCode: 100, //版本号
    };
  },
  onLaunch() {
    this.resetLoginData();
    //获取应用版本
    this.getVersionNum();
    // #ifdef H5
    //检测是否登录 h5刷新页面就是应用重启  会导致页面不走路由拦截
    this.$util.checkPage().then((isOpenPage) => {
      if (!isOpenPage) {
        uni.reLaunch({
          url: "/pages/Login/login",
        });
      }
    });
    // #endif
    this.getSystemInfo1();
    //初始化 tim
    timInit();
  },
  onShow: function () {
    const isLogin = this.$util.checkHasToken();
    this.globalData.isLogin = isLogin;
    // #ifdef APP-PLUS
    var args = plus.runtime.arguments;
    if (args) {
      if (args.startsWith("hrencai://")) {
        const path = args.replace("hrencai://", "");
        uni.navigateTo({
          url: path,
        });
        plus.runtime.arguments = "";
      }
    }
    // #endif
  },
  onHide: function () {},
  globalData: {
    isLogin: false,
    isLoadUser: false,
    user: {},
    userRole: 0,
    menus: [],
    permissions: [],
    corps: [],
    currentCorp: {},
    currentTabbarType: -1,
    tim: {
      isSDKReady: false,
      isLogin: false,
      userId: undefined,
      sdkAppId: undefined,
      userSig: undefined,
    },
    headerHeight: 0,
    statusBarHeight: 0,
    phoneInformation: {},
  },
  methods: {
    getSystemInfo1() {
      uni.getSystemInfo({
        success: (e) => {
          // 获取手机状态栏高度
          let statusBar = e.statusBarHeight;
          let customBar;
          this.globalData.phoneInformation = e;
          // #ifndef MP
          customBar = statusBar + (e.platform == "android" ? 50 : 45);
          // #endif

          // #ifdef MP-WEIXIN
          // 获取胶囊按钮的布局位置信息
          let menu = wx.getMenuButtonBoundingClientRect();
          // 导航栏高度 = 胶囊下距离 + 胶囊上距离 - 状态栏高度
          customBar = menu.bottom + menu.top - statusBar;
          // #endif

          // #ifdef MP-ALIPAY
          customBar = statusBar + e.titleBarHeight;
          // #endif

          // 注意：此方法不支持原生Nvue页面
          Vue.prototype.statusBarH = statusBar;
          Vue.prototype.customBarH = customBar;

          // 支持nvue页面写法（兼容H5/小程序/APP/APP-Nvue）
          this.globalData.statusBarH = statusBar;
          this.globalData.customBarH = customBar;
        },
      });
    },
    resetLoginData() {
      this.globalData = {
        ...this.globalData,
        isLogin: false,
        isLoadUser: false,
        user: {},
        userRole: 0,
        menus: [],
        permissions: [],
        corps: [],
        currentCorp: {},
        currentTabbarType: -1,
        tim: {
          isSDKReady: false,
          isLogin: false,
        },
        phoneInformation: {},
      };
      logger.log(`| app |  resetLoginData | globalData: ${this.globalData}`);
    },
    getVersionNum() {
      //#ifdef APP-PLUS
      // 获取本地应用资源版本号
      plus.runtime.getProperty(plus.runtime.appid, (info) => {
        this.version = info.version;
        this.versionCode = info.versionCode;
        let property = {
          version: this.version,
          versionCode: this.versionCode,
        };
        //保存版本信息
        uni.setStorageSync("setProperty", property);
        this.isGetVersionNum();
      });
      // #endif
    },
    //检测当前平台，如果是安卓则启动安卓更新
    isGetVersionNum() {
      // debugger
      let platform = uni.getSystemInfoSync().platform;
      if (platform == "ios") {
        console.log("我是iOS");
      } else if (platform == "android") {
        console.log("我是安卓");
        if (process.env.NODE_ENV !== "development") {
          this.AndroidCheckUpdate();
        }
      }
    },
    // 升级 版本
    AndroidCheckUpdate() {
      var _this = this;
      uni.request({
        url: config.domain.staticUrl + "/download/app-hrc-releaes/version.json",
        method: "GET",
        data: {},
        success: (ress) => {
          // https://source.huiguan-china.com/download/app-hrc-releaes/hrc-版本号.apk
          const lastVersion = ress.data[0].full_version;
          const appVersion = this.version;
          const isNeedUpdate = this.compairVersion(lastVersion, appVersion);
          //ress.data[0].version_serial_no > _this.versionCode
          console.log(
            `云端应用版本号：${lastVersion},当前应用版本号：${appVersion},比较结果：${
              isNeedUpdate ? "需要更新" : "不更新"
            }`
          );
          if (isNeedUpdate) {
            uni.showModal({
              title: "更新提示",
              content:
                "有新的版本发布,程序已启动自动更新。新版本下载完成后将自动弹出安装程序。",
              success: function (res) {
                if (res.confirm) {
                  var dtask = plus.downloader.createDownload(
                    config.domain.staticUrl +
                      "/download/app-hrc-releaes/hrc-" +
                      ress.data[0].full_version +
                      ".apk",
                    {},
                    function (d, status) {
                      // 下载完成
                      if (status == 200) {
                        plus.runtime.install(
                          plus.io.convertLocalFileSystemURL(d.filename),
                          {},
                          {},
                          function (error) {
                            uni.showToast({
                              title: "安装失败",
                              mask: false,
                              duration: 1500,
                            });
                          }
                        );
                      } else {
                        uni.showToast({
                          title: "更新失败",
                          mask: false,
                          duration: 1500,
                        });
                      }
                    }
                  );
                  dtask.start();
                } else if (res.cancel) {
                }
              },
            });
          }
        },
        fail: () => {},
        complete: () => {},
      });
    },
    /**
     * 比较版本大小，如果新版本versionA大于旧版本versionB则返回true，否则返回false
     * @param {String} versionA
     * @param {String} versionB
     * @return {Boolean}
     */
    compairVersion(versionA, versionB) {
      var versionsA = versionA.split(/\./g),
        versionsB = versionB.split(/\./g);
      while (versionsA.length || versionsB.length) {
        var a = Number(versionsA.shift()),
          b = Number(versionsB.shift());
        if (a == b) continue;
        return a > b || isNaN(b);
      }
      return false;
    },
  },
};
</script>

<style lang="scss">
.conten {
  border-radius: 16rpx;
  margin: 20rpx;
  overflow: hidden;

  .radius16 {
    border-radius: 16rpx;
    overflow: hidden;
  }

  .li-box {
    padding: 30rpx 30rpx;
    box-sizing: border-box;
    background-color: #fff;
    margin-bottom: 1px;
  }
}

page {
  background-color: #f1f2f6;
}

//苹方字体 	// //外部 字体 的 应用
@font-face {
  font-family: "PingFang-SC-Heavy";
  src: url(./static/font/PingFang-SC-Heavy.ttf);
}

.uni-picker-container {
  z-index: 9999999 !important;
}

view,
text {
  font-family: PingFang SC;
}

@import "@/public.scss";

/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
@import "@/uni_modules/uview-ui/index.scss";
</style>